const Router = require("koa-router");
const { Auth } = require("@middlewares/auth");
const { Goods } = require("@models/goods");
const { Op } = require("sequelize");

const router = new Router({
  prefix: "/admin/goods",
});
// 商品列表
router.post("/list", new Auth(16).m, async (ctx) => {
  const { page, pageSize, goods_name = "" } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const where = { goods_name: { [Op.like]: `%${goods_name}%` } };
  const { count: total, rows } = await Goods.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [
      ["sort", "DESC"],
      ["created_at", "DESC"],
    ], // 排序
  });

  ctx.body = {
    code: 200,
    msg: "查询成功",
    total,
    data: rows,
  };
});

// 商品详情
router.post("/detail", new Auth().m, async (ctx) => {
  const { goods_id } = ctx.request.body;
  const goods = await Goods.findOne({ where: { goods_id, is_on: true } });

  if (!goods) {
    ctx.body = {
      code: 200,
      msg: "商品不存在",
      data: null,
    };
  } else {
    ctx.body = {
      code: 200,
      msg: "查询成功",
      data: goods,
    };
  }
});

// 商品新增
router.post("/add", new Auth(16).m, async (ctx) => {
  const { goods_name, price, ...res } = ctx.request.body;
  if (!goods_name || !price) {
    throw new global.errs.AuthFailed("商品名称或价格不能为空");
  }
  await Goods.create({
    goods_name,
    price,
    ...res,
  });
  ctx.body = {
    code: 200,
    msg: "新增成功",
  };
});
// 商品编辑
router.post("/edit", new Auth(16).m, async (ctx) => {
  const { goods_id, ...res } = ctx.request.body;

  await Goods.update(
    {
      ...res,
    },
    { where: { goods_id } }
  );
  ctx.body = {
    code: 200,
    msg: "编辑成功",
  };
});

router.post("/on", new Auth(16).m, async (ctx) => {
  const { goods_id, is_on } = ctx.request.body;

  await Goods.update(
    {
      is_on,
    },
    { where: { goods_id } }
  );
  ctx.body = {
    code: 200,
    msg: is_on ? "上架成功" : "下架成功",
  };
});
// 商品删除
router.post("/delete", new Auth(16).m, async (ctx) => {
  const { goods_id } = ctx.request.body;
  if (!goods_id) {
    throw new global.errs.AuthFailed("商品ID不能为空");
  }
  await Goods.destroy({ where: { goods_id } });
  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

module.exports = router;
